import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_tv/detail_play.dart';

import 'data_loader.dart';

class WaterfallFlowRoute extends StatefulWidget {
  final int tid;

  const WaterfallFlowRoute({super.key, required this.tid});

  @override
  State<StatefulWidget> createState() => _WaterfallFlowRouteState();
}

class _WaterfallFlowRouteState extends State<WaterfallFlowRoute> {
  final List<Map<String, dynamic>> _listData = [];
  final DataLoader dataLoader = DataLoader();
  int _page = 0;
  late bool _isLoading = false;
  final ScrollController _scrollController = ScrollController();

  bool get wantKeepAlive => true;
  int selectedIndex = -1;

  Future<void> _loadData() async {
    if (_isLoading) return;
    setState(() {
      _isLoading = true;
    });
    final data = await dataLoader.loadPageData(page: _page, tid: widget.tid);
    setState(() {
      _listData.addAll(data);
      _page++;
      _isLoading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: 22 / 12,
        crossAxisSpacing: 8,
        mainAxisSpacing: 16,
      ),
      padding: const EdgeInsets.all(4.0),
      itemCount: _listData.length + 1,
      itemBuilder: (BuildContext context, int index) {
        if (index < _listData.length) {
          Map<String, dynamic> data = _listData.elementAt(index);
          return Focus(
            onKey: (FocusNode node, RawKeyEvent event) {
              if (event.logicalKey == LogicalKeyboardKey.select) {
                Navigator.pushAndRemoveUntil(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          DetailPlay(vid: data['vod_id'], tid: widget.tid)),
                  (route) => true,
                );
                return KeyEventResult.handled;
              }
              return KeyEventResult.ignored;
            },
            onFocusChange: (focused) => setState(() {
              selectedIndex = focused ? index : selectedIndex;
            }),
            child: Container(
              decoration: BoxDecoration(
                border: Border.all(
                  color: selectedIndex == index
                      ? Colors.deepOrange
                      : Colors.transparent,
                  width: 3,
                  style: BorderStyle.solid,
                ),
              ),
              width: MediaQuery.of(context).size.width,
              child: Card(
                elevation: 5,
                margin: EdgeInsets.all(0),
                color: _gradientColor(index),
                child: Stack(
                  alignment: Alignment.bottomLeft,
                  children: <Widget>[
                    ClipRRect(
                      child: Image.network(
                        data['vod_pic'].toString(),
                        fit: BoxFit.cover,
                        width: MediaQuery.of(context).size.width,
                        height: MediaQuery.of(context).size.height,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(5)),
                    ),
                    Container(
                      width: MediaQuery.of(context).size.width,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            data['vod_name'].toString(),
                            style: TextStyle(color: Colors.white, fontSize: 15),
                          ),
                          Text(
                            overflow: TextOverflow.ellipsis,
                            maxLines: 2,
                            data['vod_blurb']
                                .toString()
                                .replaceAll('&amp;nbsp;', ''),
                            style: TextStyle(color: Colors.white, fontSize: 12),
                          ),
                        ],
                      ),
                      color: _gradientColor(index).withAlpha(240),
                      padding: EdgeInsets.all(0),
                    ),
                  ],
                ),
              ),
            ),
          );
        } else {
          return _isLoading
              ? const Center(child: CircularProgressIndicator())
              : const SizedBox();
        }
      },
      controller: _scrollController,
    );
  }

  Color _gradientColor(int index) {
    int rowIndex = index ~/ 3;
    int colIndex = index % 3;

    Color color;
    if ((rowIndex + colIndex) % 3 == 0) {
      color = Colors.red;
    } else if ((rowIndex + colIndex) % 3 == 1) {
      color = Colors.orange;
    } else {
      color = Colors.green;
    }
    return color;
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _scrollController.addListener(_scrollListener);
  }

  void _scrollListener() {
    if (!_isLoading && (_scrollController.position.extentAfter == 0)) {
      _loadData();
    }
  }
}
